import React, { FC } from 'react';
import { Typography } from 'antd';
import { componentConfGroup, ComponentConfType } from '../../../components/QuestionComponents/index.ts';
import styles from './ComponentLib.module.scss';
import { addComponent } from '../../../store/componentsReducer/index.ts';
import { useDispatch } from 'react-redux';
import { nanoid } from 'nanoid';

const { Title } = Typography;

// 将 genComponent 改为 GenComponent 并作为一个 React 组件
const GenComponent: FC<{ c: ComponentConfType }> = ({ c }) => {
    const { title, type, Component, defaultProps } = c;
    const dispatch = useDispatch();

    const handleClick = () => {
        dispatch(addComponent({
            fe_id: nanoid(), // 为啥是fe_id, 因为这里的id是前端生成的nanoid(),后端mongdb不认
            title,
            type,
            props: defaultProps
        }));
    };

    return (
        <div key={type} className={styles.wrapper} onClick={handleClick}>
            <div className={styles.component}>
                <Component />
            </div>
        </div>
    );
};

// 引入分组
const Lib: FC = () => {
    return <>
        {componentConfGroup.map((group, index) => {
            const { groupId, groupName, components } = group;
            return (
                <div key={groupId}>
                    <Title level={5} style={{ marginTop: index > 0 ? '20px' : '0px' }}>
                        {groupName}
                    </Title>
                    <div>
                        {components.map((c: any) => (
                            <GenComponent key={c.type} c={c} />
                        ))}
                    </div>
                </div>
            );
        })}
    </>;
};

export default Lib;